"""
通过*.cer *..pfx 获取公钥私钥
    http://t.zoukankan.com/wangcongxing-p-12325411.html
"""

from OpenSSL import crypto

cer_file_path = r"D:cloudpayDjangoconf58543195931098400.cer"
pfx_file_path = r"F:\Download\HMCCB_daiq.pfx"


class ReadKey(object):
    """读取密钥"""

    def get_public_key(cer_file_path):
        """
        从cer证书中提取公钥
        :param cer_file: cer证书存放的路径
        :return: 公钥
        """
        cert = crypto.load_certificate(crypto.FILETYPE_ASN1, open(cer_file_path, "rb").read())
        res = crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey()).decode("utf-8")
        return res.strip()

    def get_private_key(pfx_file_path, password="daiq123hmccb"):
        """
        从pfx证书中提取私钥,如果证书已加密，需要输入密码
        :param pfx_file_path:pfx证书存放的路径
        :param password:证书密码
        :return:私钥pkey = crypto.load_pkcs12(key, password).get_privatekey()
        """
        pfx = crypto.load_pkcs12(open(pfx_file_path, 'rb').read(), bytes(password, encoding="utf8"))
        res = crypto.dump_privatekey(crypto.FILETYPE_PEM, pfx.get_privatekey())
        return res.strip()


# print(ReadKey.get_public_key(cer_file_path))

print(ReadKey.get_private_key(pfx_file_path))


"""
der pem cer crt key pfx等概念及区别
    https://blog.51cto.com/wushank/1915795

    1、从pfx导出crt和key:
    
        操作命令(若 pfx 有密码则会提示输入密码)：
        openssl pkcs12 -in example.cn.ssl.pfx -nocerts -nodes -out example.key
        openssl pkcs12 -in example.cn.ssl.pfx -clcerts -nokeys -out example.crt
    
    2、将crt和key合并出pfx:
    
        操作命令：
        openssl pkcs12 -export -in certificate.crt -inkey privateKey.key -out certificate.pfx

"""
